<?php
namespace app\api\service\wine;

use app\api\model\user\Grade as UserGradeModel;
use app\common\library\helper;
use app\common\service\BaseService;
use app\api\model\wine\User as UserModel;
use app\store\model\ApplyGrade as ApplyGradeModel;

class ApplyGrade extends BaseService{
    /**
     * 判断升级条件
     * @param int $grade_id
     * @param float $expend_money
     * @param int $pcount
     * @return bool
     * @throws \app\common\exception\BaseException
     */
    private static function checkGrade(int $grade_id,float $expend_money, int $pcount): bool
    {
        $upgradeJson = UserGradeModel::where(['grade_id'=>$grade_id])->value('upgrade');
        $upgradeArr = helper::jsonDecode($upgradeJson);
        $pcountCondition = $upgradeArr['pcount'];
        $autoCondition = $upgradeArr['auto'];
        $expend_moneyCondition = $upgradeArr['expend_money'];
        if($autoCondition == 1){
            // 自动模式下忽略
            throwError('自动升级模式，无需申请!');
        }
        // 判断下线人数
        if($pcount >= $pcountCondition){
            return true;
        }
        // 判断消费金额
        if($expend_money >= $expend_moneyCondition){
            return true;
        }
        return false;
    }

    /**
     * 检查升级条件
     * @param int $user_id
     * @param int $grade_id
     * @return bool
     * @throws \app\common\exception\BaseException
     */
    public static function check(int $user_id,int $grade_id){
        $r = UserModel::getCurrentCondition($user_id,$grade_id);
        $expend_money = $r['expend_money'];
        $pcount = $r['pcount'];
        $condition = self::checkGrade($grade_id,$expend_money,$pcount);
        if($condition){
            // 添加申请记录
            return ApplyGradeModel::add(getStoreId(),$user_id,$grade_id);
        }else{
            return false;
        }
    }
}
